const User = require('../../models/user')
const jwt = require('../../jwt')

module.exports = (req, res) => {
  const username = req.body.username
  const password = req.body.password
  // console.log(req.body)

  User.findOne({
    username,
    password
  }, (err, userDoc) => {
    if (err) {
      return res.status(500).json({
        err_code: 500,
        message: err.message
      })
    }
    // 若没有此项数据
    if (!userDoc) {
      return res.status(200).json({
        err_code: 1,
        message: 'Email or password is invalid.'
      })
    }
    // 验证用户
    if (userDoc.username === 'feng' && userDoc.password === '123') {
      // 验证成功,生成token,发送给客户端
      const token = jwt.generateToken(userDoc.username, userDoc._id)
      res.status(200).json({
        err_code: 0,
        token,
        data:userDoc,
        message: 'success'
      })
    } else {
      res.status(200).json({
        err_code: 2,
        message: '你无权登陆'
      })
    }

  })
}